//
//  NetworkTools.swift
//  测试-05-AFN Swift
//
//  Created by male on 15/10/15.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import AFNetworking

/// HTTP 请求方法枚举
enum HMRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}
// MARK: 网络工具
class NetworkTools: AFHTTPSessionManager {

    // MARK: - 应用程序信息
    private let appKey = "246575435"
    private let appSecret = "9f27ee2e553cce993fcc9464ce28af07"
    private let redirectUrl = "http://www.baidu.com"
    
    /// 网络请求完成回调，类似于 OC 的 typeDefine
    typealias HMRequestCallBack = (result: AnyObject?, error: NSError?)->()
    
    // 单例
    static let sharedTools: NetworkTools = {
        
        let tools = NetworkTools(baseURL: nil)
        
        // 设置反序列化数据格式 - 系统会自动将 OC 框架中的 NSSet 转换成 Set
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    /// 返回token的字典
//    private var tokenDict: [String: AnyObject]? {
//    // 判断 token是否有效
//        if let token = SYLJUserAccountViewModel.sharedUserAccountViewModel.accessToken {
//            return ["access_token": token]
//        }
//        return nil
//    }
}

//  MARK: - 发布微博
extension NetworkTools {
    /// 发布微博
    ///
    /// - parameter status:   微博文本
    /// - parameter finished: 完成回调
    /// - see: [http://open.weibo.com/wiki/2/statuses/update](http://open.weibo.com/wiki/2/statuses/update)
    func sendStatus(status: String,image: UIImage?,finished: HMRequestCallBack) {
        //1, 创建参数字典
        var params = [String: AnyObject]()
       
        // 2,设置参数
        params["status"] = status
        // 3,判断是否有图片要上传
        if image == nil {
            let urlString = "https://api.weibo.com/2/statuses/update.json"
            
            // 3,发起网络请求
            tokenRequest(.POST, URLString: urlString, parameters: params, finished: finished)
        } else {
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            let data = UIImagePNGRepresentation(image!)
            upload(urlString, data: data!, name: "pic", parameters: params, finished: finished)
        }
    }
}

// MARK: - 微博数据相关方法
extension NetworkTools {
    
    /// 加载微博数据
    ///
    /// since_id	若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    /// max_id      若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
    /// - parameter finished: 完成回调
    /// - see: [http://open.weibo.com/wiki/2/statuses/home_timeline](http://open.weibo.com/wiki/2/statuses/home_timeline)
    func loadStatus(since_id since_id: Int,max_id: Int,finished: HMRequestCallBack) {
        
        //1, 创建参数字典
        var params = [String: AnyObject]()
        // 将since_id和max_id拼接到参数字典中
        if since_id > 0 {
            params["since_id"] = since_id
        }else if max_id > 0 {
            params["max_id"] = max_id
        }
        
        // 2. 准备网络参数
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        // 3. 发起网络请求
        tokenRequest(.GET, URLString: urlString, parameters: params, finished: finished)
    }
}

// MARK: 用户相关方法
extension NetworkTools {
    
    ///  加载用户信息
    ///
    ///  - parameter accesstoken: accesstoken
    ///  - parameter uid:         uid
    ///  - parameter finished:    完成的回调
    /// - see: [http://open.weibo.com/wiki/2/users/show](http://open.weibo.com/wiki/2/users/show)
    func loadUserInfo(accesstoken: String,uid: String,finished:HMRequestCallBack) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token": accesstoken,"uid": uid];
        request(.GET, URLString: urlString, parameters: parameters, finished: finished)
    }
}

// MARK: - OAuth 相关方法
extension NetworkTools {
    
    /// OAuth 授权 URL
    /// - see: [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var oauthURL: NSURL {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
        
        return NSURL(string: urlString)!
    }
    
    /// 加载 AccessToken
    func loadAccessToken(code: String, finished: HMRequestCallBack) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": appKey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUrl]
        
        request(.POST, URLString: urlString, parameters: params, finished: finished)
//        // 测试返回的数据类型,AFN默认的响应格式是JSON,会直接反序列化
//        // 如果要确认返回的数据的格式问题,需要改变AFN的数据处理的格式
//        // 如果是NSNumber,则没有引号,这在做KVC的操作中非常重要
//        // 1>设置AFN返回的数据位二进制数据
//        responseSerializer = AFHTTPResponseSerializer()
//        // 2>发起网络请求
//        POST(urlString, parameters: params, success: { (_, regist) -> Void in
//            // 将二进制数据转化为字符串
//            let json = NSString(data: regist as! NSData, encoding: NSUTF8StringEncoding)
//            print(json)
//            }, failure: nil)
    }
}

// MARK: - 封装 AFN 网络方法
extension NetworkTools {
    
    private func tokenRequest(method: HMRequestMethod, URLString: String, var parameters: [String: AnyObject]?, finished: HMRequestCallBack) {
        // 判断 token是否有效
        guard let token = SYLJUserAccountViewModel.sharedUserAccountViewModel.accessToken else {
            // 如果字典为 nil，通知调用方，token 无效
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
            
            return
        }
        // 设置 parameters 字典
        // 1, 判断字典是否有值
        if parameters == nil {
            parameters = [String: AnyObject]()
        }
        parameters!["access_token"] = token
        
        // 发起网络请求
        request(method, URLString: URLString, parameters: parameters, finished: finished)
    }


    /// 网络请求
    ///
    /// - parameter method:     GET / POST
    /// - parameter URLString:  URLString
    /// - parameter parameters: 参数字典
    /// - parameter finished:   完成回调
    private func request(method: HMRequestMethod, URLString: String, parameters: [String: AnyObject]?, finished: HMRequestCallBack) {
        
        // 定义成功回调
        let success = { (task: NSURLSessionDataTask, result: AnyObject) -> Void in
            finished(result: result, error: nil)
        }
        
        // 定义失败回调
        let failure = { (task: NSURLSessionDataTask, error: NSError) -> Void in
            // 在开发网络应用的时候，错误不要提示给用户，但是错误一定要输出！
            print(error)
            finished(result: nil, error: error)
        }
        
        if method == HMRequestMethod.GET {
            GET(URLString, parameters: parameters, success: success, failure: failure)
        } else {
            POST(URLString, parameters: parameters, success: success, failure: failure)
        }
    }
    
    /// 上传文件
    private func upload(URLString: String,data: NSData,name: String, var parameters: [String: AnyObject]?, finished: HMRequestCallBack) {
        // 设置参数
        // 1. 设置 token 参数 －> 将 token 添加到 parameters 字典中
        // 判断 token 是否有效
        guard let token = SYLJUserAccountViewModel.sharedUserAccountViewModel.accessToken else {
            // token 无效
            // 如果字典为 nil，通知调用方，token 无效
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
            
            return
        }
        if parameters == nil {
            parameters = [String: AnyObject]()
        }
        
        parameters!["access_token"] = token
        
        // 发送网络请求
        POST(URLString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
            formData.appendPartWithFileData(data, name: name, fileName: "xxx", mimeType: "application/octet-stream")
            
            }, success: { (_, result) -> Void in
                finished(result: result, error: nil)
            }) { (_, error) -> Void in
                print(error)
                finished(result: nil, error: error)
        }
    }
}
